const { escape } = require('querystring')

const [request, crypto, cheerio] = [
  require('request-promise-native'),
  require('crypto'),
  require('cheerio')
]
const accessKey = [
  'xonfwb',
  'bcxvkk',
  'daghlq',
  'rtyqez',
  'xirlia',
  'omqfmb',
  'wnuwhd',
  'papyat',
  'mvfkjy',
  'jwtjyd',
  'gxrbql',
  'zlapnl',
  'evvozm',
  'zoazxm',
  'afdidb',
  'znamvb',
  'avnddk',
  'hmrwyu',
  'toaaje', // 给浩华俱乐部
  'zejflo' //给刘晓
]
async function getAliCookie (headers) {
  let r = await request({
    method: 'get',
    url: 'https://cha.cheng.xin/credit/publicCreditSearch.htm',
    resolveWithFullResponse: true,
    headers: headers
  })
  const txt = r.body //`window['_tb_token_'] = '2OZ0jm6V-6umEjOU5FVV6KXlZcysa7ixigf8';`
  const reg = /window\[\'_tb_token_\'\] = \'(.+)\';/g
  reg.test(txt)

  //console.log(txt)

  //console.log('新获取_tb_token_:', RegExp.$1)
  const tokenStr = RegExp.$1
  const cookie = r.headers['set-cookie'].join('; ')
  console.log('cookie:', cookie, '新获取_tb_token_:', RegExp.$1)
  return [cookie, tokenStr]
}
async function getAliCompany (comName) {
  if (!comName) {
    return []
  }
  const headers = {
    'X-Requested-With': 'XMLHttpRequest',
    Accept: 'application/json',
    'Accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'user-agent':
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
  }

  const nowDate = $.now()
  if (!global.companyGetNameAliApi) {
    global.companyGetNameAliApi = {
      t: nowDate,
      c: await getAliCookie(headers)
    }
  } else {
    if (nowDate - global.companyGetNameAliApi.t > 60000) {
      global.companyGetNameAliApi = {
        t: nowDate,
        c: await getAliCookie(headers)
      }
    } else {
      //do nothing
    }
  }

  headers.cookie = global.companyGetNameAliApi.c[0]
  r = await request({
    method: 'post',
    url:
      'https://xinyong.1688.com/credit/creditsearch/recommend.json?_tb_token_=' +
      global.companyGetNameAliApi.c[1],
    json: true,
    headers: headers,
    form: {
      key: comName
    }
  })
  return r.data.map(x => x.value).filter(Boolean)
}
async function getBaiduCompany (comName) {
  if (!comName) {
    return []
  }
  const headers = {
    Accept:
      'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'user-agent':
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
  }

  let companyName = encodeURIComponent(comName)
  r = await request({
    method: 'post',
    url: `https://xin.baidu.com/s?q=${companyName}&t=0`,
    json: true,
    headers: headers
  })
  const reg = /title=\"(.+)\" data\-log\-an=\"company\"/gm
  const $$ = cheerio.load(r, { ignoreWhitespace: true, xmlMode: true })
  const arr = []
  $$('.zx-list-item-url').each(function (i, elem) {
    arr.push($$(this).text())
  })
  return arr
}
async function getAliCompanyInfo (comName) {
  if (!comName) {
    return []
  }

  /*
  content-length: 100
  cookie: _tb_token_=y9dyBLefRi4wbW50-lrozAZ1; cna=BDxHGqwRPTwCAbSppVKU4nzZ; xlly_s=1; UM_distinctid=1807f473723fa0-091a9320fbe373-53580614-13c680-1807f4737241bbc; CNZZDATA1257121278=226169069-1651396865-https%253A%252F%252Fxinyong.1688.com%252F%7C1651396865; x5sec=7b2262697a6372656469743b32223a223633656536373261343236306337343334396339333231343465326465333730434b3768755a4d47454d766c314c7172342b33716644444a795a69752b762f2f2f2f3842227d; isg=BMDArbhEtu2ClErpgn_aOhbakUiSSaQT76KsUjpT_lt2tWjf-V1ko7LDzR11MVzr
*/

  const headers = {
    accept: 'application/json',
    'cache-control': 'no-cache',
    //referer: 'https://cha.cheng.xin/credit/publicCreditSearch.htm?key=',
    origin: 'https://cha.cheng.xin',
    'x-requested-with': 'XMLHTTPREQUEST',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    //'accept-encoding': 'gzip, deflate, br',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'user-agent':
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36'
  }

  const nowDate = $.now()
  if (!global.companyGetNameAliApi) {
    global.companyGetNameAliApi = {
      t: nowDate,
      c: await getAliCookie(headers)
    }
  } else {
    if (nowDate - global.companyGetNameAliApi.t > 60000) {
      global.companyGetNameAliApi = {
        t: nowDate,
        c: await getAliCookie(headers)
      }
    } else {
      //do nothing
    }
  }

  headers.cookie = global.companyGetNameAliApi.c[0]
  let esName = encodeURI(comName)
  //headers.Referer = headers.Referer + esName
  console.log(global.companyGetNameAliApi, esName)

  r = await request({
    method: 'post',
    url:
      //'https://xinyong.1688.com/credit/creditsearch/query.json?_tb_token_=' +
      'https://cha.cheng.xin/credit/creditsearch/query.json?_tb_token_=' +
      global.companyGetNameAliApi.c[1],

    headers: headers,
    form: {
      page: 1,
      total: 1,
      size: 10,
      key: esName,
      areaCode: '',
      industryPhy: '',
      entStatus: '',
      enableAggregate: true
    }
  })
  /*
    for (let i = 0; i < r.data.cardList.length; i++) {
      if (r.data.cardList[i].entName === comName || r.data.cardList[i].entNameOld === comName) {
        return r.data.cardList[i]
      }
    }*/
  return r
}
module.exports = {
  async getName (ctx) {
    const { key, getType, name } = ctx.checkedData.data
    let r
    if (!accessKey.includes(key)) {
      ctx.status = 405
      return
    }
    if (getType === 'baidu') {
      r = await getBaiduCompany(name)
      ctx.ok(r)
      return
    }
    if (getType === 'ali') {
      r = await getAliCompany(name)
      console.log(r, name)

      ctx.ok(r)
      return
    }
    ctx.throwCode(400, '参数不正确')
  },
  async getInfo (ctx) {
    const { key, name } = ctx.checkedData.data
    let r
    if (!accessKey.includes(key)) {
      ctx.status = 405
      return
    }
    r = await getAliCompanyInfo(name)
    console.log(r, name)

    ctx.ok(r)
    return
  }
}

// 扩展函数
